<template>
  <div class="app-container">
    <el-card shadow="never">
      <template #header>
        <div class="card-header">
          <h3>新增支付记录</h3>
        </div>
      </template>
      
      <el-form 
        ref="formRef" 
        :model="form" 
        :rules="rules" 
        label-width="120px"
        label-position="right"
        status-icon
        v-loading="loading"
      >
        <el-divider content-position="left">基本信息</el-divider>
        
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="支付编号" prop="paymentId">
              <el-input 
                v-model="form.paymentId" 
                placeholder="系统自动生成" 
                disabled
              />
            </el-form-item>
          </el-col>
          
          <el-col :span="8">
            <el-form-item label="支付方式" prop="paymentMethod">
              <el-select v-model="form.paymentMethod" placeholder="请选择支付方式" style="width: 100%">
                <el-option label="现金" value="现金" />
                <el-option label="微信" value="微信" />
                <el-option label="支付宝" value="支付宝" />
                <el-option label="医保" value="医保" />
                <el-option label="银行卡" value="银行卡" />
              </el-select>
            </el-form-item>
          </el-col>
          
          <el-col :span="8">
            <el-form-item label="支付金额" prop="amount">
              <el-input-number 
                v-model="form.amount" 
                :min="0" 
                :precision="2" 
                :step="10" 
                style="width: 100%"
                @change="updateTotalAmount"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-divider content-position="left">患者信息</el-divider>
        
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="患者" prop="patientId">
              <el-select 
                v-model="form.patientId"
                filterable
                remote
                placeholder="搜索患者"
                :remote-method="searchPatients"
                :loading="patientSelectLoading"
                style="width: 100%"
              >
                <el-option
                  v-for="item in patientOptions"
                  :key="item.id"
                  :label="`${item.name} (${item.patientId})`"
                  :value="item.id"
                >
                  <div>{{ item.name }} ({{ item.patientId }})</div>
                  <small>{{ item.gender }}, {{ item.age }}岁</small>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          
          <el-col :span="8">
            <el-form-item label="部门" prop="departmentId">
              <el-select v-model="form.departmentId" filterable placeholder="请选择部门" style="width: 100%">
                <el-option
                  v-for="item in departmentOptions"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-divider content-position="left">支付项目</el-divider>
        
        <el-table
          :data="form.items"
          border
          style="width: 100%; margin-bottom: 20px"
        >
          <el-table-column label="项目类型" width="200">
            <template #default="scope">
              <el-select v-model="scope.row.type" placeholder="选择类型" style="width: 100%">
                <el-option label="挂号费" value="registration" />
                <el-option label="处方费" value="prescription" />
                <el-option label="病历费" value="medical_record" />
                <el-option label="服务费" value="service" />
                <el-option label="其他费用" value="other" />
              </el-select>
            </template>
          </el-table-column>
          
          <el-table-column label="关联项目ID" width="300">
            <template #default="scope">
              <el-input v-model="scope.row.itemId" placeholder="关联项目ID" />
            </template>
          </el-table-column>
          
          <el-table-column label="金额">
            <template #default="scope">
              <el-input-number 
                v-model="scope.row.amount" 
                :min="0" 
                :precision="2" 
                :step="10" 
                style="width: 100%"
                @change="updateTotalAmount"
              />
            </template>
          </el-table-column>
          
          <el-table-column label="操作" width="100">
            <template #default="scope">
              <el-button
                type="danger"
                link
                @click="removeItem(scope.$index)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        
        <div class="form-actions">
          <el-button type="primary" @click="addItem">添加项目</el-button>
        </div>
        
        <el-divider content-position="left">总计</el-divider>
        
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="总金额" prop="totalAmount">
              <el-input-number 
                v-model="form.totalAmount" 
                :min="0" 
                :precision="2" 
                :step="10" 
                style="width: 100%"
                disabled
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <div class="form-actions">
          <el-button @click="goBack">取消</el-button>
          <el-button type="primary" @click="submitForm" :loading="submitting">提交</el-button>
        </div>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { paymentAPI, patientAPI, departmentAPI } from '@/utils/api'

const router = useRouter()

// 表单数据
const formRef = ref(null)
const loading = ref(false)
const submitting = ref(false)

// 下拉选项
const patientOptions = ref([])
const patientSelectLoading = ref(false)
const departmentOptions = ref([])

// 表单数据
const form = reactive({
  paymentId: '',
  patientId: '',
  departmentId: '',
  amount: 0,
  totalAmount: 0,
  paymentMethod: '现金',
  items: [
    {
      type: 'registration',
      itemId: '',
      amount: 0
    }
  ]
})

// 表单验证规则
const rules = {
  patientId: [
    { required: true, message: '请选择患者', trigger: 'change' }
  ],
  paymentMethod: [
    { required: true, message: '请选择支付方式', trigger: 'change' }
  ],
  amount: [
    { required: true, message: '请输入支付金额', trigger: 'blur' }
  ]
}

// 加载部门列表
const fetchDepartments = async () => {
  try {
    const res = await departmentAPI.getDepartments()
    if (res.data && res.data.success) {
      departmentOptions.value = res.data.data.departments || []
    }
  } catch (error) {
    console.error('获取部门列表失败', error)
  }
}

// 搜索患者
const searchPatients = async (query) => {
  if (query.length < 2) return
  
  patientSelectLoading.value = true
  try {
    const res = await patientAPI.searchPatients({ query })
    if (res.data && res.data.success) {
      patientOptions.value = res.data.data.patients || []
    }
  } catch (error) {
    console.error('搜索患者失败', error)
  } finally {
    patientSelectLoading.value = false
  }
}

// 添加支付项目
const addItem = () => {
  form.items.push({
    type: 'other',
    itemId: '',
    amount: 0
  })
}

// 移除支付项目
const removeItem = (index) => {
  form.items.splice(index, 1)
  updateTotalAmount()
}

// 更新总金额
const updateTotalAmount = () => {
  let total = form.amount || 0
  
  form.items.forEach(item => {
    total += item.amount || 0
  })
  
  form.totalAmount = total
}

// 提交表单
const submitForm = async () => {
  await formRef.value.validate(async (valid) => {
    if (!valid) return
    
    submitting.value = true
    try {
      const paymentData = {
        patientId: form.patientId,
        amount: form.amount,
        totalAmount: form.totalAmount,
        paymentMethod: form.paymentMethod,
        items: form.items.filter(item => item.amount > 0 && item.type)
      }
      
      if (form.departmentId) {
        paymentData.departmentId = form.departmentId
      }
      
      const res = await paymentAPI.createPayment(paymentData)
      
      if (res.data && res.data.success) {
        ElMessage.success('支付记录创建成功')
        router.push('/payments/list')
      } else {
        ElMessage.error(res.data.message || '创建支付记录失败')
      }
    } catch (error) {
      console.error('创建支付记录失败', error)
      ElMessage.error('创建支付记录失败')
    } finally {
      submitting.value = false
    }
  })
}

// 返回上一页
const goBack = () => {
  router.back()
}

// 生命周期钩子
onMounted(() => {
  fetchDepartments()
})
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.form-actions {
  display: flex;
  justify-content: center;
  margin-top: 20px;
  gap: 20px;
}
</style> 